package com.lqw.vhr.service;

import com.lqw.dto.EmpDTO;
import com.lqw.dto.MailConstants;
import com.lqw.vhr.mapper.EmployeeMapper;
import com.lqw.vhr.model.*;
import com.lqw.vhr.utils.POIUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    NationService nationService;

    @Autowired
    PoliticsstatusService politicsstatusService;

    @Autowired
    DepartmentService departmentService;

    @Autowired
    PositionService positionService;

    @Autowired
    JobLevelService jobLevelService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    MailSendLogService mailSendLogService;


    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    DecimalFormat decimalFormat = new DecimalFormat("##.00");

    //emp => data
    public RespPageBean getEmployeeByPage(Integer page, Integer size, Employee employee, Date[] beginDateScope) {
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<Employee> data = employeeMapper.getEmployeeByPage(page, size, employee, beginDateScope);
        for (Employee emp : data) {
            emp.setNationName(emp.getNation().getName());
            emp.setDeptName(emp.getDepartment().getName());
            emp.setPosName(emp.getPosition().getName());
            emp.setPoliticName(emp.getPoliticsstatus().getName());
            emp.setJobLevelName(emp.getJobLevel().getName());
        }
        Long total = employeeMapper.getTotal(employee, beginDateScope);
        RespPageBean bean = new RespPageBean();
        bean.setData(data);
        bean.setTotal(total);
        return bean;
    }

    @Transactional
    public int addEmp(Employee employee) {
        Date beginContract = employee.getBeginContract();
        Date endContract = employee.getEndContract();
        double month = (Double.parseDouble(yearFormat.format(endContract)) - Double.parseDouble(yearFormat.format(beginContract))) * 12 + (Double.parseDouble(monthFormat.format(endContract)) - Double.parseDouble(monthFormat.format(beginContract)));
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(month / 12)));
        int result = employeeMapper.insertSelective(employee);
        if (result == 1) {
            Employee emp = employeeMapper.getEmployeeById(employee.getId());
            EmpDTO empDTO = new EmpDTO()
                    .setDepName(emp.getDepartment().getName())
                    .setEmail(emp.getEmail())
                    .setEmpName(emp.getName())
                    .setJobLevelName(emp.getJobLevel().getName())
                    .setPosName(emp.getPosition().getName());
//            empDTO.setDepName(emp.getDepartment().getName());
//            empDTO.setEmail(emp.getEmail());
//            empDTO.setEmpName(emp.getName());
//            empDTO.setJobLevelName(emp.getJobLevel().getName());
//            empDTO.setPosName(emp.getPosition().getName());
            //生成消息的唯一id
            String msgId = UUID.randomUUID().toString();
            MailSendLog mailSendLog = new MailSendLog();
            mailSendLog.setMsgId(msgId);
            mailSendLog.setCreateTime(new Date());
            mailSendLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailSendLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailSendLog.setEmpId(emp.getId());
            mailSendLog.setTryTime(new Date(System.currentTimeMillis() + 1000 * 60 * MailConstants.MSG_TIMEOUT));
            mailSendLogService.insert(mailSendLog);
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME, empDTO, new CorrelationData(msgId));
        }
        return result;
    }

    public int deleteEmpByEid(Integer id) {
        return employeeMapper.deleteByPrimaryKey(id);
    }

    public int updateEmp(Employee employee) {
        return employeeMapper.updateByPrimaryKeySelective(employee);
    }

    public Integer maxWorkID() {
        return employeeMapper.maxWorkID();
    }

    public Integer addEmps(List<Employee> list, boolean isExcelObj) {
        if (isExcelObj) {
            Map<String, Integer> nationMap = new HashMap<>();
            Map<String, Integer> politicsStatusMap = new HashMap<>();
            Map<String, Integer> depMap = new HashMap<>();
            Map<String, Integer> positionMap = new HashMap<>();
            Map<String, Integer> jobLevelMap = new HashMap<>();
            initMap(nationMap, politicsStatusMap, depMap, positionMap, jobLevelMap);
            for (Employee employee : list) {
                employee.setNationId(nationMap.get(employee.getNationName()));
                employee.setPoliticId(politicsStatusMap.get(employee.getPoliticName()));
                employee.setDepartmentId(depMap.get(employee.getDeptName()));
                employee.setPosId(positionMap.get(employee.getPosName()));
                employee.setJobLevelId(jobLevelMap.get(employee.getJobLevelName()));
                //计算工作年限
                Date beginContract = employee.getBeginContract();
                Date endContract = employee.getEndContract();
                double month = (Double.parseDouble(yearFormat.format(endContract)) - Double.parseDouble(yearFormat.format(beginContract))) * 12 + (Double.parseDouble(monthFormat.format(endContract)) - Double.parseDouble(monthFormat.format(beginContract)));
                employee.setContractTerm(Double.parseDouble(decimalFormat.format(month / 12)));
            }
        }
        return employeeMapper.addEmps(list);
    }

    public void initMap(Map<String, Integer> nationMap, Map<String, Integer> politicsStatusMap, Map<String, Integer> depMap, Map<String, Integer> positionMap, Map<String, Integer> jobLevelMap
    ) {
        List<Nation> nations = nationService.getAllNations();
        List<Politicsstatus> politicsstatus = politicsstatusService.getAllPoliticsstatus();
        List<Department> deps = departmentService.getAllDepartmentsWithOutChildren();
        List<Position> positions = positionService.getAllPositions();
        List<JobLevel> jobLevels = jobLevelService.getAllJobLevels();
        nations.forEach(nation -> nationMap.put(nation.getName(), nation.getId()));
        politicsstatus.forEach(politicsStatus -> politicsStatusMap.put(politicsStatus.getName(), politicsStatus.getId()));
        deps.forEach(dep -> depMap.put(dep.getName(), dep.getId()));
        positions.forEach(position -> positionMap.put(position.getName(), position.getId()));
        jobLevels.forEach(jobLevel -> jobLevelMap.put(jobLevel.getName(), jobLevel.getId()));
    }


    public RespPageBean getEmployeeByPageWithSalary(Integer page, Integer size) {
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<Employee> list = employeeMapper.getEmployeeByPageWithSalary(page, size);
        RespPageBean respPageBean = new RespPageBean();
        respPageBean.setData(list);
        respPageBean.setTotal(employeeMapper.getTotal(null, null));
        return respPageBean;
    }

    public Integer updateEmployeeSalaryById(Integer eid, Integer sid) {
        return employeeMapper.updateEmployeeSalaryById(eid, sid);
    }

    public Employee getEmployeeById(Integer empId) {
        return employeeMapper.getEmployeeById(empId);
    }
}
